<template>
  <div>
    <el-card>
      <el-form :inline="true" class="form">
        <el-form-item label="用户名：">
          <el-input placeholder="请输入用户名" v-model="keyword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="!keyword" @click="search">
            搜索
          </el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top: 20px">
      <el-button type="primary" @click="addUser">添加用户</el-button>
      <el-button
        type="danger"
        :disabled="!selctIdArr.length"
        @click="deletSelectUser"
      >
        批量删除
      </el-button>
      <!-- 展示用户信息 -->
      <el-table
        style="width: 100%"
        border
        :data="userArr"
        @selection-change="selectChange"
      >
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column
          label="用户名"
          align="center"
          prop="name"
        ></el-table-column>
        <el-table-column
          label="用户名称"
          align="center"
          prop="username"
        ></el-table-column>
        <el-table-column
          label="用户角色"
          align="center"
          prop="roleName"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
        ></el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
        ></el-table-column>
        <el-table-column label="操作" width="200px">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" @click="setRole(row)">
              分配
            </el-button>
            <el-button type="primary" size="small" @click="updateUser(row)">
              编辑
            </el-button>
            <el-popconfirm
              :title="`确认删除${row.name}?`"
              @confirm="deleteUser(row.id)"
            >
              <template #reference>
                <el-button type="primary" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 7, 9, 11]"
      :background="true"
      layout="prev, pager, next,jumper,->,sizes,total"
      :total="total"
      @current-change="getHasUser"
      @size-change="getHasUser()"
    ></el-pagination>
    <!-- 抽屉结构：添加修改用户 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
      </template>
      <template #default>
        <el-form :model="userParams" :rules="rules" ref="formRef">
          <el-form-item label="用户姓名" prop="username">
            <el-input
              placeholder="请输入用户姓名"
              v-model="userParams.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input
              placeholder="请输入用户昵称"
              v-model="userParams.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
            <el-input
              placeholder="请输入用户密码"
              v-model="userParams.password"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button type="primary" @click="save">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </template>
    </el-drawer>
    <!-- 抽屉结构：角色分配 -->
    <el-drawer v-model="roleDrawer">
      <template #header>
        <h4>分配角色</h4>
      </template>
      <template #default>
        <el-form>
          <el-form-item label="用户姓名">
            <el-input v-model="userParams.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色列表">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>
            <el-checkbox-group
              v-model="userRole"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="(role, index) in allRole"
                :key="index"
                :label="role"
              >
                {{ role.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button type="primary" @click="saveRole">确定</el-button>
        <el-button>取消</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue'
import {
  reqUserInfo,
  reqAddOrUpdateUser,
  reqAllRole,
  reqSetUserRole,
  reqRemoveUser,
  reqSelectUser,
} from '@/api/acl/user'
import type {
  User,
  UserResponseData,
  AllRoleResponseData,
  AllRole,
  SetRoleData,
} from '@/api/acl/user/type'
import { ElMessage } from 'element-plus'
let pageNo = ref<number>(1)
let pageSize = ref<number>(5)
let total = ref<number>(0)
// 存储全部用户的数组
let userArr = ref<User[]>([])
// 收集用户信息的响应式数据
let userParams: User = reactive({
  username: '',
  name: '',
  password: '',
})
// 定义控制抽屉的显示与隐藏
let drawer = ref<boolean>(false)
let roleDrawer = ref<boolean>(false)
// 获取form组件实例
let formRef = ref()
// 存储全部职位的数据
let allRole = ref<AllRole>([])
// 当前用户已有的职位
let userRole = ref<AllRole>([])
// 存储批量删除的id
let selctIdArr = ref<User[]>([])
// 收集用户输入的关键字
let keyword = ref<string>('')
// 获取全部已有的用户信息
const getHasUser = async (pager: number = 1) => {
  // 收集当前页码
  pageNo.value = pager
  let result: UserResponseData = await reqUserInfo(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code == 200) {
    total.value = result.data.total
    userArr.value = result.data.records
  }
}
onMounted(() => {
  getHasUser()
})
// 添加用户按钮的回调
const addUser = () => {
  drawer.value = true
  Object.assign(userParams, {
    id: 0,
    username: '',
    name: '',
    password: '',
  })
  // 清除上一次错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}
// 更新已有的用户按钮的回调
const updateUser = (row: User) => {
  drawer.value = true
  // 存储收集已有的账号信息
  Object.assign(userParams, row)
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
  })
}
// 保存按钮的回调
const save = async () => {
  // 确保表单校验通过
  formRef.value.validate()
  let result: any = await reqAddOrUpdateUser(userParams)
  if (result.code == 200) {
    drawer.value == false
    ElMessage({
      type: 'success',
      message: userParams.id ? '更新成功' : '添加成功',
    })
    // 浏览器自动刷新一次
    window.location.reload()
  } else {
    drawer.value == false
    ElMessage({
      type: 'error',
      message: userParams.id ? '更新失败' : '添加失败',
    })
  }
}
// 取消按钮的回调
const cancel = () => {
  drawer.value = false
}
// 校验用户名字的回调函数
const validatorUsername = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户名至少五位'))
  }
}
// 校验用户昵称的回调函数
const validatorName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('昵称至少五位'))
  }
}
// 校验用户密码的回调函数
const validatorPassword = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 6) {
    callback()
  } else {
    callback(new Error('密码至少六位'))
  }
}
// 表单校验规则对象
const rules = {
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  name: [{ required: true, trigger: 'blur', validator: validatorName }],
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}
// 分配角色按钮的回调
const setRole = async (row: User) => {
  // 存储已有的用户信息
  Object.assign(userParams, row)
  // 获取全部的职位的数据与当前用户已有的职位的数据
  let result: AllRoleResponseData = await reqAllRole(userParams.id as number)
  if (result.code == 200) {
    // 存储全部的职位
    allRole.value = result.data.allRolesList
    // 存储当前用户已有的职位
    userRole.value = result.data.assignRoles
    roleDrawer.value = true
  }
}
// 收集顶部复选框全选数据
const checkAll = ref<boolean>(false)
// 控制顶部全选复选框不确定的样式
const isIndeterminate = ref<boolean>(true)
// 顶部全部复选框的change事件
const handleCheckAllChange = (val: boolean) => {
  userRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}
// 顶部全部的复选框的change事件
const handleCheckedCitiesChange = (value: string) => {
  // 顶部复选框的勾选数据
  const checkedCount = value.length
  // 代表：勾选上的项目个数与全部的职位个数相等，顶部的复选框勾选上
  checkAll.value = checkedCount == allRole.value.length
  // 不确定的样式
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allRole.value.length
}
// 确定按钮的回调
const saveRole = async () => {
  let data: SetRoleData = {
    userId: userParams.id as number,
    roleIdList: userRole.value.map((item) => item.id as number),
  }
  // 分配用户职位
  let result: any = await reqSetUserRole(data)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '分配角色成功' })
    roleDrawer.value = false
    getHasUser(pageNo.value)
  } else {
    ElMessage({ type: 'error', message: '分配角色失败' })
  }
}
// 删除某个用户
const deleteUser = async (userId: number) => {
  let result: any = await reqRemoveUser(userId)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '删除成功' })
    roleDrawer.value = false
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({ type: 'error', message: '删除失败' })
  }
}
// table复选框勾选的时候会触发的事件
const selectChange = (value: any) => {
  selctIdArr.value = value
}
// 批量删除按钮的回调
const deletSelectUser = async () => {
  // 整理批量删除的参数
  let idsList: any = selctIdArr.value.map((item) => item.id)
  // 批量删除的请求
  let result: any = await reqSelectUser(idsList)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '删除成功' })
    roleDrawer.value = false
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
// 搜索按钮的回调
const search = () => {
  // 根据关键字获取相应的用户数据
  getHasUser()
  keyword.value = ''
}
// 重置按钮
const reset = () => {
  keyword.value = ''
  getHasUser()
}
</script>

<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-form-item {
    margin-bottom: 0px;
  }
}
</style>
